<div class="row">
    <div class="col-lg-12">
        <h3 class="page-header">Nhập tích điểm</h3>
    </div>
    <!-- /.col-lg-12 -->
</div>
<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-12">
                        <form role="form" method="POST" name="AddOrder" onsubmit="return checkinput();">
                            <div class="form-group">
                                <div class="row">                                                                       
                                      
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="row">
                                     <div class="col-lg-2">
                                        <label>Bên mua</label>
                                    </div>
                                    <div class="col-lg-3" id="store_name">
                                        <?php echo $this->storeHTML; ?>
                                    </div>
                                    <div class="col-lg-2">
                                        <label>Bên bán</label>
                                    </div>
                                     <div class="col-lg-3">
                                        <?php echo $this->agentHTML; ?>
                                    </div>                                                                         
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-lg-2">
                                        <label>Ngày mua hàng</label>
                                    </div>
                                    <div class="col-lg-3">
                                        <input class="form-control" type="datetime" name="order_created" id="order_created" value="" >
                                    </div>
                                    <div class="col-lg-2">
                                        <label>DS Sản phẩm</label>
                                    </div>
                                      <div class="col-lg-3">
                                        <?php echo $this->productHTML ?>
                                    </div>                                    
                                </div>
                            </div>
                             <div class="form-group">
                                <div class="row">                                     
                                      <div class="col-lg-2">
                                        <label>Số lượng</label>
                                    </div>
                                    <div class="col-lg-3" id="quantity_id">
                                        <input id="quantity" class="form-control" name="quantity" onkeydown="change_text();" onkeyup="change_text();">
                                    </div>
                                    <div class="col-lg-2">
                                        <label>Hệ số điểm</label>
                                    </div>
                                    <div class="col-lg-3" id="factor_id">
                                        <input id="factor" class="form-control" name="factor" onkeydown="change_text();" onkeyup="change_text();" readonly="true">
                                    </div>                                    
                                </div>
                            </div>   
                            <div class="form-group">
                                <div class="row">                                                                          
                                    <div class="col-lg-2">
                                        <label>Điểm nhận được</label>
                                    </div>
                                      <div class="col-lg-3" id="charges_id">
                                        <input id="charges" class="form-control" name="charges" readonly="true"> 
                                      </div>                                    
                                </div>
                            </div>
                            <div class="form-group">
                                <button onclick="return add();" type="button" class="btn btn-primary">Thêm mới</button>
                                <button type="reset" class="btn btn-default">Đặt lại</button>
                                <button onclick="return showModal(1);" type="button" class="btn btn-default">Thêm cửa hàng mới</button>
                                <button onclick="return showModal(2);" type="button" class="btn btn-default">Thêm đại lý mới</button>
                            </div>                            
                           
                            <table id="order_table" class="table table-hover">     
                                <tr class="success">                                    
                                    <td>Đại lý</td>
                                    <td>Sản phẩm</td>
                                    <td>Hệ số điểm</td>
                                    <td>Số lượng</td> 
                                    <td>Điểm nhận được</td>
                                    <td>Ngày mua hàng</td>
                                    <td>Huỷ</td>
                                </tr>
                            </table> 
                            <div class="form-group">
                                <button onclick="return addOrder();" type="button" class="btn btn-primary">Lưu đơn hàng</button>                                
                            </div>  
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>   
</div>

<form  id="addAgent" method="POST" onsubmit="if(document.getElementById('AgentorStore').innerHTML == 'Thêm đại lý mới') return checkAgent(2); else return checkAgent(1);">
    <div id="myModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;</button>
                    <h4 class="modal-title">
                        <center>
                            <div id="AgentorStore">                                
                            </div>                            
                        </center>
                    </h4>
                </div>
                <div class="modal-body">    
                    
                    <div class="row">
                        <div class="col-lg-3">                            
                            Tên
                        </div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="agent_name" name="oldpassword" /></div>
                    </div>
                    
                    <div class="row">
                        <div class="col-lg-3">
                            Địa chỉ</div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="agent_address" name="password" /></div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Khu vực</div>
                        <div class="col-lg-9">
                            <?php echo $this->popupareaHTML ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Tỉnh thành</div>
                        <div class="col-lg-9">
                            <?php echo $this->popupprovinceHTML ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Quận huyện</div>
                        <div class="col-lg-9">
                            <?php echo $this->popupdistrictHTML ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Người đại diện</div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="representavie" name="repassword" /></div>                       
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Số điện thoại</div>
                        <div class="col-lg-9">
                            <input class="form-control"  id="phone" name="repassword" /></div>                       
                    </div>
                    <div class="row">
                        <div class="col-lg-3">
                            Loại đại lý</div>
                        <div class="col-lg-9">
                            <?php echo GlobalLib::getCombo('agent_cat_id', 'agent_category', 'id', 'name', 0,false,'',null,'class="form-control"') ?> 
                        <div class="col-lg-2">
                            <span style="color: Red;"></span></div>
                    </div>
                </div>                    
                <div class="modal-footer">    
                    <center>
                        <button  class="btn btn-primary" type="submit">
                            Thêm
                        </button>
                        <button type="button" id="close" class="btn btn-default" data-dismiss="modal">
                            Đóng
                        </button>
                    </center>
                </div>
            </div>
        </div>
    </div>
</form>
<script type="text/javascript">
$(document).ready(function(){
    $("#quantity").keydown(function (e) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
                         // Allow: Ctrl+A
                        (e.keyCode == 65 && e.ctrlKey === true) || 
                         // Allow: home, end, left, right
                        (e.keyCode >= 35 && e.keyCode <= 39)) {
                             // let it happen, don't do anything
                             return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                });
            $("#order_created").datepicker({
                dateFormat: "dd-mm-yy",
                onSelect: function() {
                                   var params = {
                    action:'getproduct',
                    agent_id: $('#agent_id').val(),
                    product_id:$('#product_id').val(),
                    order_created:$('#order_created').val()
                };
                $.post('<?php echo $this->baseUrl() ?>/kinhdoanh/service/index', params,
                            function (data) {
                                 var items = eval(data);
                                var jItem = items[0];
                               $('#product_id').html(jItem.html);
                               $('#charges_id').html(jItem.html3);
                               $('#factor_id').html(jItem.html1);
                               $('#quantity_id').html(jItem.html2);
                            });
            }
            });
        });
        $('#store_id').multiselect({
            includeSelectAllOption:true,
            enableFiltering: true,
            maxHeight: '300',
            buttonText: function(options) 
            {
                var retStr = "";
                if (options.length === 0) {
                   retStr = "None selected";
                } else if(options.length <=1){
                   var textArray = [];
                   $.each(options,function(key,value){
                       textArray.push($.trim($(value).html()));
                   });
                   retStr = "<div class='pull-left restricted'>"+textArray.join(",")+"</div>";
                } else {
                   retStr = options.length+" selected";
                }
                return retStr+" <b class='caret'></b>";
            }  
        });
        $('#agent_id').multiselect({
            includeSelectAllOption:true,
            enableFiltering: true,
            maxHeight: '300',
            buttonText: function(options) 
            {
                var retStr = "";
                if (options.length === 0) {
                   retStr = "None selected";
                } else if(options.length <=1){
                   var textArray = [];
                   $.each(options,function(key,value){
                       textArray.push($.trim($(value).html()));
                   });
                   retStr = "<div class='pull-left restricted'>"+textArray.join(",")+"</div>";
                } else {
                   retStr = options.length+" selected";
                }
                return retStr+" <b class='caret'></b>";
            }  
        });
function change_text()
{
    var quantity= $('#quantity').val();
    var factor=$('#factor').val();
    var charges=quantity*factor;
     var n=parseFloat(charges);
    x = Math.round(n * 1000)/1000;
    document.getElementById('charges').value=x;
}
function showModal(cat)
{
    if(cat=="2") document.getElementById("AgentorStore").innerHTML = "Thêm đại lý mới";
    else if(cat=="1") document.getElementById("AgentorStore").innerHTML = "Thêm cửa hàng mới";
    $('#myModal').modal('show');
};
function checkAgent(cat)
{        
    if($("#agent_name").val()==="") {bootbox.alert("Vui lòng nhập tên của đại lý"); return false;};
    var paramss =
    {
        name: $("#agent_name").val(),
        address: $("#agent_address").val() ,
        area_id: $("#popup_area_id").val(),
        province_id: $("#popup_province_id").val(),
        district_id: $("#popup_district_id").val(),
        representavie: $("#representavie").val(),
        phone: $("#phone").val(),
        agent_cat_id: $("#agent_cat_id").val()
    };
    
    $.post('<?php echo $this->baseUrl()."/kinhdoanh/order/addagent" ?>',paramss,function(data){        
        $('#myModal').modal('hide');
        if(cat=="2")            
            $("#agent_id").append("<option value='"+data+"' selected='selected'>"+$("#agent_name").val()+"</option>");
        else if(cat=="1") $("#store_id").append("<option value='"+data+"' selected='selected'>"+$("#agent_name").val()+"</option>");
    });
    event.preventDefault();
};
</script>
<script type="text/javascript">                                
                             document.forms['AddOrder'].name.focus();
                             function set_focus() {
                                 document.forms['AddOrder'].name.focus();
                             }
                             function add(){                                    
                                 if($("#store_id").val()==$("#agent_id").val())
                                 {
                                     bootbox.alert("Vui lòng chọn cửa hàng và đại lý khác nhau!");
                                     return false;
                                 }
                                 if($("#store_id").val()=="0")
                                 {
                                     bootbox.alert("Vui lòng chọn cửa hàng");
                                     return false;
                                 }
                                 if($("#agent_id").val()=="0")
                                 {
                                     bootbox.alert("Vui lòng chọn đại lý");
                                     return false;
                                 }
                                 if($("#product_id").val()=="0")
                                 {
                                     bootbox.alert("Vui lòng chọn sản phẩm");
                                     return false;
                                 }
                                 if($("#factor").val()=="")
                                 {
                                     bootbox.alert("Sản phẩm này chưa được thiết lập hệ số điểm");
                                     return false;
                                 }
                                 if($("#quantity").val()=="" || isNaN($("#quantity").val())==true)
                                 {
                                     bootbox.alert("Vui lòng nhập số lượng");
                                     return false;
                                 }               
                                 var exist =true;                                    
                                 for(var i=1;i<=document.getElementById("order_table").rows.length-1;i++)
                                 {                                        
                                     if( $("#agent"+i).val() == $("#agent_id").val() && $("#product"+i).val() ==$("#product_id").val() &&
                                             $("#order_created").val() == $("#order_created"+i).val())
                                     {
                                         $("#quantity"+i).val(parseInt($("#quantity"+i).val())+parseInt($("#quantity").val()));
                                         $("#charges"+i).val(parseInt($("#charges"+i).val())+parseInt($("#charges").val()));
                                         document.getElementById("p_quantity"+i).innerHTML = $("#quantity"+i).val().toString();
                                         document.getElementById("p_charges"+i).innerHTML = $("#charges"+i).val().toString();
                                         exist=false;
                                         break;
                                     }
                                 }
                                 if(exist)
                                 {
                                     document.getElementById("order_table").innerHTML = 
                                       document.getElementById("order_table").innerHTML
                                       +"<tr id='line"+document.getElementById("order_table").rows.length+"' class='info'>"                                            
                                         +"<td ><input id='agent"+document.getElementById("order_table").rows.length+"' type='hidden' value='"+$("#agent_id").val()+"'>"+$("#agent_id option:selected").text()+"</td>"
                                         +"<td ><input id='product"+document.getElementById("order_table").rows.length+"' type='hidden' value='"+$("#product_id").val()+"'>"+$("#product_id option:selected").text()+"</td>"
                                         +"<td ><input id='factor"+document.getElementById("order_table").rows.length+"' type='hidden' value='"+$("#factor").val()+"'>"+$("#factor").val()+"</td>"
                                         +"<td ><input id='quantity"+document.getElementById("order_table").rows.length+"' type='hidden' value='"+$("#quantity").val()+"'><p id='p_quantity"+document.getElementById("order_table").rows.length+"'>"+$("#quantity").val()+"</p></td>"
                                         +"<td ><input id='charges"+document.getElementById("order_table").rows.length+"' type='hidden' value='"+$("#charges").val()+"'><p id='p_charges"+document.getElementById("order_table").rows.length+"'>"+$("#charges").val()+"</p></td>"
                                         +"<td ><input id='order_created"+document.getElementById("order_table").rows.length+"' type='hidden' value='"+$("#order_created").val()+"'><p id='p_order_created"+document.getElementById("order_table").rows.length+"'>"+$("#order_created").val()+"</p></td>"
                                         +"<td><a onclick='return $(\"#line"+document.getElementById("order_table").rows.length+"\").remove();' class='fa fa-trash-o  fa-lg' href='#'></a></td>"
                                       +"</tr>";
                                 }                                                         
//                                 $("#agent_id").val(0);
                                 $("#product_id").val(0);
                                 $("#factor").val("");
                                 $("#quantity").val("");
                                 $("#charges").val("");                                    
                                 $("#store_id").attr("disabled","disabled");
                                 $('#store_id').multiselect('disable');
                             };
</script>
        <script>
        function addOrder()
        {                                                               
            if(document.getElementById("order_table").rows.length-1 == 0)
            {
                bootbox.alert("Chưa có sản phẩm nào được chọn!");
                return false;
            }      
            var totalcharges = 0;
            for (var i=1;i<= document.getElementById("order_table").rows.length-1 ; i++)
            {
                totalcharges = totalcharges+ parseInt($("#charges"+i).val());
            }
            var param = {
                store_id: $("#store_id").val(),
                total_charges:totalcharges
            };
             var flag=0;
        $.ajax({
        url: "<?php echo $this->baseUrl() ?>/kinhdoanh/order/addorder",
        type: 'POST',
        async:false,
        data: param,
        beforeSend:function(){
        $('html').addClass('ajaxLoader-inner');
        },
        success: function(data) {

        flag=flag+1;
        for (var i = 1; i <= document.getElementById("order_table").rows.length - 1; i++){
        var params = {
        order_no: data.trim(),
        product_id: $("#product" + i).val(),
        quantity: $("#quantity" + i).val(),
        agent_id: $("#agent" + i).val(),
        factor: $("#factor" + i).val(),
        charges: $("#charges" + i).val(),
        order_created: $("#order_created" + i).val()
        };
        $.ajax({
        url: "<?php echo $this->baseUrl() ?>/kinhdoanh/order/adddetail",
        type: 'POST',
        async:false,
        data: params,
        success: function(data) {
        flag=flag+1;
        } 
        });
        }
        } 
        });
        if(flag==document.getElementById("order_table").rows.length){
        window.location = "<?php echo $this->baseUrl() . '/kinhdoanh/order/index' ?>";
        }
        };
        </script>

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        